package org.example.myportfolio.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.myportfolio.config.response.JsonResult;
import org.example.myportfolio.pojo.param.WorksParam;
import org.example.myportfolio.pojo.vo.WorkVO;
import org.example.myportfolio.service.WorkService;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Validated
@RequestMapping("/api/v1/works")
public class WorkController {

    @Autowired
    private WorkService workService;

    /**
     * 保存或更新作品
     * @param worksParam
     * @return
     */
    @PostMapping("saveOrUpdate")
    public JsonResult saveOrUpdateWork(@Validated @RequestBody WorksParam worksParam) {
        log.debug("作品入参 ID：{}",worksParam.getId());
        if(ObjectUtils.isNull(worksParam)){
            log.error("作品入参为空");
            return JsonResult.fail("作品内容不能为空！");
        }

            if(worksParam.getId() == null) {
                Long workId = workService.createWork(worksParam);
                return JsonResult.ok("创建成功"+workId);
            }else {
            workService.updateWork(worksParam);
            return JsonResult.ok("更新成功");
            }

    }

    /**
     * 删除作品
     */
    @PostMapping("delete/{workId}")
    public JsonResult deleteWork(@PathVariable("workId") Long workId) {
        log.debug("删除作品入参：{}",workId);
        //校验workId是否为空 workId是Long类型
        if(workId == null){
            return JsonResult.fail("删除作品id不能为空！");
        }
        workService.deleteWork(workId);
        return JsonResult.ok("删除成功");
    }

    /**
     * 分页查询作品
     * 将查询结构放到redis中，减少对数据库的访问
     */
    @PostMapping("page")
    public JsonResult pageWork(@Range(min = 1,max = 100,message = "页码不能小于1或大于100")
                                   @RequestParam("pageNum") Integer pageNum,
                                    @RequestParam ("pageSize") Integer pageSize){
        log.debug("分页查询作品入参：{}{}",pageNum,pageSize);
        List<WorkVO> workVOList = workService.pageWork(pageNum,pageSize);
        return JsonResult.ok(workVOList);
    }


    /**
     * 基于es的全文检索查询作品
     */
    @PostMapping("search")
    public JsonResult searchWork(@RequestParam("keyword") String keyword){
        log.debug("全文检索入参：{}",keyword);
        List<WorkVO> workVOList = workService.searchWorkByEs(keyword);
        return JsonResult.ok(workVOList);
    }






}
